from flask import Blueprint,request,jsonify
from db import db1
from utils.acl import acl
from utils.user_role import user_role
from utils.abac import abac


bp_resource = Blueprint('resource',__name__)


@bp_resource.route('/resourcelist',methods=['POST','GET'])
def resourcelist():
    if request.method == 'GET':
        data = acl.get_pagedelist()
        return jsonify({'code':200,'list':data})
    else:
        res = request.json
        data = acl.update_resource(res['userid'],res['reslist'])
        return jsonify({'code':200})

@bp_resource.route('/user_res')
def user_res():
    user_id = request.args.get('user_id')
    sql = "select resource_id from user_res where user_id=%d"%int(user_id)
    res = db1.find_all(sql)
    list1 = []
    for i in res:
        list1.append(i['resource_id'])
    return jsonify({'code':200,'list':list1})



@bp_resource.route('/config_user_role',methods=['POST','GET'])
def config_user_role():
    data = request.json
    user_role.set_user_role(data['user_id'],data['urlist'])
    return jsonify({'code':200})


@bp_resource.route('/rolelist',methods=['POST','GET'])
def rolelist():
    sql = "select * from role "
    res = db1.find_all(sql)
    return jsonify({'code':200,'list':res})

@bp_resource.route('/role_res',methods=['POST','GET'])
def role_res():
    data = request.json
    abac.set_role_resource(data['role_id'],data['reslist'])
    return jsonify({'code':200})
